package com.imu.wys.dao;

import com.imu.wys.model.User;
import com.imu.wys.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {

    /**
     * 查询结果为 1个时调用的方法。
     *
     * @param sql  查询语句
     * @return user对象
     */
    public User searchOne(String sql){
        User user = null;
        Connection connection = DBUtil.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            //接收结果集
            resultSet = preparedStatement.executeQuery();
            //遍历结果集
            while(resultSet.next()) {
                user = new User();
                user.setUserid(resultSet.getInt("userid"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            //关闭资源
            DBUtil.close(resultSet);
            DBUtil.close(preparedStatement);
            DBUtil.close(connection);
        }
        return user;
    }
}
